package cn.dwj.mongo2.demo;

import com.mongodb.*;

import java.util.regex.Pattern;

/**
 * Created by Administrator on 2017/12/12 0012.
 */
public class mongoDemo {
    public static void main(String[] args) throws Exception{
        //配置连接数据库的主机名和端口号
        MongoClient client = new MongoClient("192.168.72.145", 27000);
        //连接数据库
        DB db = client.getDB("admin");
        for(String name : db.getCollectionNames()){
            System.out.println("集合名字：" + name);
        }

        DBCollection col = db.getCollection("dwj");//操作集合的名称
        //保存
        for (int i=0; i<9; i++){
            BasicDBObject obj = new BasicDBObject();
            obj.append("tid", 1000+i);
            obj.append("tname", "d_"+i);
            obj.append("address", "广东_"+i);
            col.insert(obj);
        }

        //查询
        DBCursor cursor = col.find();
        //分页查询
        DBCursor cursor1 = col.find().skip(0).limit(10);
        //条件查询
        DBObject cond = new BasicDBObject();
        cond.put("tid", new BasicDBObject("$gte", 1000).append("$lte", 1010));//数据范围在1000 - 1020中间
        cond.put("tid", new BasicDBObject("$in", new int[]{1000, 1003, 1004}));//查询数据集合
        Pattern p = Pattern.compile("5");
        cond.put("tname", new BasicDBObject("$regex", p));//模糊查询带5
        DBCursor cursor2 = col.find(cond);

        while (cursor.hasNext()){
            DBObject o = cursor.next();
            System.out.println("名称:"+o.get("tname"));
        }

        //数据修改
        DBObject cond1 = new BasicDBObject();//设置要修改的条件过滤条件
        cond1.put("tid", 1004);
        DBObject cond2 = new BasicDBObject();//修改器设置
        cond2.put("$set", new BasicDBObject("tname", "wwww"));
        WriteResult result = col.update(cond1, cond2);
        WriteResult result1 = col.updateMulti(cond, cond2);//修改多行
        System.out.println(result.getN());

        //删除
        col.remove(cond);

        //关闭数据库连接
        client.close();
    }
}
